from django.db.models import Sum
from django.http import JsonResponse
from django.shortcuts import render
# Create your views here.
from django.views import View
from rest_framework.permissions import IsAdminUser
from rest_framework.response import Response
from rest_framework.views import APIView
from datetime import date, timedelta

from apps.users.models import User
from apps.goods.models import GoodsCategory, GoodsVisitCount


class UserDailyActiveCountView(APIView):
    permission_classes = [IsAdminUser]

    def get(self, request):
        to_date = date.today()
        count = User.objects.filter(last_login__gte=to_date).count()
        return Response({'count': count, 'date': to_date})


class UserDailyOrderCountView(APIView):
    permission_classes = [IsAdminUser]

    def get(self, request):
        to_date = date.today()
        count = User.objects.filter(orderinfo__create_time__gte=to_date).count()
        return Response({'count': count, 'date': to_date})


class UserTotalCountView(APIView):
    permission_classes = [IsAdminUser]

    def get(self, request):
        to_date = date.today()
        count = User.objects.count()
        return Response({'count': count, 'date': to_date})


class UserDailyIncrementCountView(APIView):
    permission_classes = [IsAdminUser]

    def get(self, request):
        to_date = date.today()
        count = User.objects.filter(date_joined__gte=to_date).count()
        return Response({'count': count, 'date': to_date})


class UserMonthIncrementCountView(APIView):
    permission_classes = [IsAdminUser]

    def get(self, request):
        to_date = date.today()
        start_date = to_date - timedelta(days=30)
        data_list = []
        for i in range(30):
            # 循环遍历获取当天日期
            index_date = start_date + timedelta(days=i)
            # 指定下一天日期
            next_date = start_date + timedelta(days=i + 1)
            count = User.objects.filter(date_joined__gte=index_date, date_joined__lt=next_date).count()
            data_list.append({
                'count': count,
                'date': index_date
            })
        return Response(data_list)
        # return JsonResponse(data=data_list, safe=False)


class GoodsDailyViews(APIView):
    def get(self, request):
        categorys = GoodsCategory.objects.filter().all()
        data_list = []
        for category in categorys:
            count = GoodsVisitCount.objects.filter(category=category).aggregate(Sum('count'))['count__sum']
            data_list.append({
                'category': category.name,
                'count': count if count else 0
            })
        data_list.sort(key=lambda x: x['count'], reverse=True)
        return Response(data_list[:10])
